package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.PeachVoice;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;

@DubboService
public class PeachVoiceApiImpl implements PeachVoiceApi {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * @param peachVoice : 语音文件
     * @return: void
     * @description:
     * @author: Mr.ChiZi
     * @date: 2021/11/27 4:37 下午
     */
    @Override
    public String save(PeachVoice peachVoice) {
        peachVoice.setVid(idWorker.getNextId("voiceId"));
        peachVoice.setCreated(System.currentTimeMillis());

        mongoTemplate.save(peachVoice);

        return peachVoice.getId().toHexString();
    }

    /**
     * @param count : 随机查询语音的剩余条数
     * @param userId
     * @return: com.tanhua.model.mongo.PeachVoice
     * @description: 随机抽取一条语音
     * @author: Mr.ChiZi
     * @date: 2021/11/27 8:04 下午
     */
    @Override
    public PeachVoice randomVoice(int count, Long userId) {
        //1、创建统计对象，设置统计参数
        //设置条件，语音未读过,不是自己的语音
        Criteria criteria = Criteria.where("alreadRead").is(false).and("userId").nin(userId);

        TypedAggregation aggregation = Aggregation.newAggregation(PeachVoice.class, Aggregation.match(criteria), Aggregation.sample(count));

        //2、调用mongoTemplate方法统计
        AggregationResults<PeachVoice> peachVoices = mongoTemplate.aggregate(aggregation, PeachVoice.class);
        //3、获取统计结果
        return peachVoices.getUniqueMappedResult();
    }

    //语音阅后即焚，保证只被一个人阅读
    @Override
    public void remove(PeachVoice peachVoice) {
        mongoTemplate.remove(peachVoice);
    }
}
